package com.ciccwm.log.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;

/**
 * 敏感信息处理工具类
 */
@Slf4j
public class SensitiveUtils {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final String MASK = "******";

    private SensitiveUtils() {
    }

    /**
     * 对JSON字符串中的敏感字段进行脱敏处理
     *
     * @param json       JSON字符串
     * @param maskFields 需要脱敏的字段名
     * @return 脱敏后的JSON字符串
     */
    public static String desensitize(String json, String[] maskFields) {
        if (json == null || json.isEmpty() || maskFields == null || maskFields.length == 0) {
            return json;
        }

        try {
            JsonNode rootNode = objectMapper.readTree(json);
            if (rootNode.isObject()) {
                ObjectNode objectNode = (ObjectNode) rootNode;
                for (String field : maskFields) {
                    if (objectNode.has(field)) {
                        objectNode.put(field, MASK);
                    }
                }
                return objectNode.toString();
            }
            return json;
        } catch (Exception e) {
            log.error("Desensitize JSON string failed", e);
            return json;
        }
    }
} 